//
//  DGGTelecomLoginViewController.m
//  DGGMobileLoginSDK
//
//  Created by dgg_hzk on 2019/12/16.
//

#import "DGGTelecomLoginViewController.h"
#import "DGGMobileLoginServiceViewController.h"
#import "DGGMobileLoginViewController.h"
#import "DGGMobileLoginSDKPrefixHeader.h"

#define kScreenWidth [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height

@interface DGGTelecomLoginViewController ()<UITextViewDelegate>

@property (nonatomic, strong) UIImageView *logoImageView;
@property (nonatomic, strong) UILabel *phoneNumberLabel;
@property (nonatomic, strong) UILabel *serverLabel;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIButton *otherLoginButton;
@property (nonatomic, strong) UIButton *checkAgreeButton;
@property (nonatomic, strong) UITextView *agreeLabel;
@property (nonatomic, assign) BOOL isAgree;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;

@property (nonatomic, strong) UIColor *navColor;
@property (nonatomic, strong) UIColor *navTextColor;
@property (nonatomic, strong) UIColor *pageThemeColor;
@property (nonatomic, strong) UIFont *navTextFont;
@property (nonatomic, strong) UIImage *backImage;

@property (nonatomic, strong) UIColor *loginButtonBgColor;
@property (nonatomic, strong) UIColor *otherBtnTextColor;
@property (nonatomic, copy) NSString *otherBtnText;

@property (nonatomic, strong) UIColor *appPrivacyContentColor;
@property (nonatomic, strong) UIColor *appPrivacyColor;

@property (nonatomic, strong) NSArray *appPrivacyArray;


@end

@implementation DGGTelecomLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configNavigationBar];
    
    [self initUI];
    
    [self bindData];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //隐藏导航栏分割线
    for (UIView *view in self.navigationController.navigationBar.subviews) {
        if (CGRectGetHeight([view frame]) <= 1) {
            view.hidden = YES;
        }
    }
    [self dgg_fetchAuthorAction];
}

- (void)configNavigationBar{
    self.title = [DGGMobileLoginConfig sharedInstance].navTitle;
    self.navColor = [DGGMobileLoginConfig sharedInstance].navColor;
    self.navTextColor = [DGGMobileLoginConfig sharedInstance].navTextColor;
    self.pageThemeColor = [DGGMobileLoginConfig sharedInstance].pageThemeColor;
    self.navTextFont = [DGGMobileLoginConfig sharedInstance].navTextFont;
    self.loginButtonBgColor = [DGGMobileLoginConfig sharedInstance].loginButtonBgColor;
    self.otherBtnText = [DGGMobileLoginConfig sharedInstance].switchBtnText;
    self.otherBtnTextColor = [DGGMobileLoginConfig sharedInstance].switchBtnTextColor;
    self.appPrivacyContentColor = [DGGMobileLoginConfig sharedInstance].appPrivacyContentColor;
    self.appPrivacyColor = [DGGMobileLoginConfig sharedInstance].appPrivacyColor;
    self.appPrivacyArray = [DGGMobileLoginConfig sharedInstance].appPrivacyArray;
    self.backImage = [DGGMobileLoginConfig sharedInstance].navBackImage;
    if(!self.backImage){
        self.backImage = [UIImage imageNamed:kMobileLoginSource(@"mobileLogin_close_white.png")];
    }
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = self.navColor;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:self.navTextColor,
                                                                    NSFontAttributeName:self.navTextFont};
    UIButton *backBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBarButton setImage:self.backImage forState:UIControlStateNormal];
    [backBarButton setImage:self.backImage forState:UIControlStateHighlighted];
    [backBarButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    view.userInteractionEnabled = YES;
    [view addSubview:backBarButton];
    backBarButton.frame = view.bounds;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
}

- (void)dgg_fetchAuthorAction{
    self.activityIndicator.frame = CGRectMake((kScreenWidth-40)*0.5, CGRectGetMaxY(self.logoImageView.frame), 40, 40);
    [self.activityIndicator startAnimating];
    //预取号操作
    [[NTESQuickLoginManager sharedInstance] getPhoneNumberCompletion:^(NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.activityIndicator stopAnimating];
            NSNumber *boolNum = [resultDic objectForKey:@"success"];
            BOOL success = [boolNum boolValue];
            if (success) {
                self.phoneNumberLabel.text = [resultDic objectForKey:@"securityPhone"];
                [self.activityIndicator stopAnimating];
            } else {
                __weak typeof(self) weakSelf = self;
                [self dismissViewControllerAnimated:YES completion:^{
                    [weakSelf sendNextHander:DGGMobileLoginStatusPreGetPhoneFailure token:nil errorInfo:resultDic];
                }];
            }
        });
    }];
}

- (void)initUI{
    self.view.backgroundColor = [UIColor whiteColor];
    CGFloat heightScale = 0.0f;
    if(kScreenHeight == 812.0f){
        heightScale = (kScreenHeight / 812.0f);
    }else{
        heightScale = kScreenHeight / 667.0f;
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth-80)*0.5, 140*heightScale, 80, 80)];
    imageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:imageView];
    
    self.logoImageView = imageView;
    
    CGRect phoneLabelFrame = CGRectMake(0, CGRectGetMaxY(self.logoImageView.frame), kScreenWidth, 40);
    UILabel *phoneLabel = [[UILabel alloc] initWithFrame:phoneLabelFrame];
    phoneLabel.textAlignment = NSTextAlignmentCenter;
    phoneLabel.backgroundColor = [UIColor whiteColor];
    phoneLabel.textColor = [UIColor colorWithRed:51/255.0f green:51/255.0f blue:51/255.0f alpha:1.0];
    if (@available(iOS 8.2, *)) {
        phoneLabel.font = [UIFont systemFontOfSize:21.0f weight:UIFontWeightMedium];
    } else {
        // Fallback on earlier versions
        phoneLabel.font = [UIFont boldSystemFontOfSize:21.0f];
    }
    [self.view addSubview:phoneLabel];
    
    self.phoneNumberLabel = phoneLabel;
    
    CGRect serverLabelFrame = CGRectMake(0, CGRectGetMaxY(self.phoneNumberLabel.frame), kScreenWidth, 20);
    UILabel *serverLabel = [[UILabel alloc] initWithFrame:serverLabelFrame];
    serverLabel.textAlignment = NSTextAlignmentCenter;
    serverLabel.backgroundColor = [UIColor clearColor];
    serverLabel.textColor = [[UIColor grayColor] colorWithAlphaComponent:0.6];
    if (@available(iOS 8.2, *)) {
        serverLabel.font = [UIFont systemFontOfSize:12.0f weight:UIFontWeightMedium];
    } else {
        // Fallback on earlier versions
        serverLabel.font = [UIFont systemFontOfSize:12.0f];
    }
    serverLabel.text = dianxinServiceDomain;
    [self.view addSubview:serverLabel];
    
    self.serverLabel = serverLabel;
    
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginButton setTitle:[DGGMobileLoginConfig sharedInstance].loginButtonText forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    CGRect loginButtonFrame = CGRectMake((kScreenWidth-(kScreenWidth-100))*0.5, CGRectGetMaxY(self.serverLabel.frame)+7, (kScreenWidth-100), 38);
    loginButton.frame = loginButtonFrame;
    loginButton.backgroundColor = self.loginButtonBgColor;
    if (@available(iOS 8.2, *)) {
        loginButton.titleLabel.font = [UIFont systemFontOfSize:18.0f weight:UIFontWeightRegular];
    } else {
        loginButton.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    }
    loginButton.layer.cornerRadius = 5.0f;
    loginButton.layer.masksToBounds = YES;
    [loginButton addTarget:self action:@selector(loginButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginButton];
    
    self.loginButton = loginButton;
    
    UIButton *otherLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [otherLoginButton setTitle:self.otherBtnText forState:UIControlStateNormal];
    [otherLoginButton setTitleColor:self.otherBtnTextColor forState:UIControlStateNormal];
    CGRect otherLoginButtonFrame = CGRectMake((kScreenWidth-100)*0.5, CGRectGetMaxY(self.loginButton.frame)+10, 100, 38);
    otherLoginButton.frame = otherLoginButtonFrame;
    otherLoginButton.backgroundColor = [UIColor clearColor];
    if (@available(iOS 8.2, *)) {
        otherLoginButton.titleLabel.font = [UIFont systemFontOfSize:15.0f weight:UIFontWeightRegular];
    } else {
        otherLoginButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    }
    [otherLoginButton addTarget:self action:@selector(otherLoginButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:otherLoginButton];
    self.otherLoginButton = otherLoginButton;
    
    UITextView *agreeLabel = [[UITextView alloc] initWithFrame:CGRectZero];
    CGRect agreeLabelFrame = CGRectMake(50, kScreenHeight - 80, kScreenWidth-50-28, 60);
    agreeLabel.frame = agreeLabelFrame;
    agreeLabel.font = [UIFont systemFontOfSize:12.0f];
    agreeLabel.textColor = [[UIColor grayColor] colorWithAlphaComponent:0.6];
    agreeLabel.contentMode = UIViewContentModeCenter;
    agreeLabel.dataDetectorTypes = UIDataDetectorTypeLink;
    agreeLabel.backgroundColor = [UIColor whiteColor];
    agreeLabel.selectable = YES;
    agreeLabel.editable = NO;
    [self.view addSubview:agreeLabel];
    self.agreeLabel = agreeLabel;
    
    UIButton *checkAgreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [checkAgreeButton setImage:[UIImage imageNamed:kMobileLoginSource(@"mobileLogin_checked.png")] forState:UIControlStateNormal];
    CGRect checkAgreeButtonFrame = CGRectMake(CGRectGetMinX(self.agreeLabel.frame)-22, CGRectGetMinY(self.agreeLabel.frame)+7, 17, 17);
    checkAgreeButton.frame = checkAgreeButtonFrame;
    checkAgreeButton.backgroundColor = [UIColor clearColor];
    [self.view addSubview:checkAgreeButton];
    self.checkAgreeButton = checkAgreeButton;
    [self.checkAgreeButton addTarget:self action:@selector(checkAgreeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.isAgree = YES;//默认选中
}

#pragma mark - 登录事件
- (void)loginButtonAction:(UIButton *)sender{
    if(!self.isAgree){
        [self showToastWithMsg:@"请阅读并同意协议"];
    }else{
        [[NTESQuickLoginManager sharedInstance] CUCMCTAuthorizeLoginCompletion:^(NSDictionary * _Nonnull resultDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSNumber *boolNum = [resultDic objectForKey:@"success"];
                BOOL success = [boolNum boolValue];
                if (success) {
                    __weak typeof(self) weakSelf = self;
                    [self dismissViewControllerAnimated:YES completion:^{
                        NSString *token = [resultDic objectForKey:@"accessToken"];
                        [weakSelf sendNextHander:DGGMobileLoginStatusSuccess token:token errorInfo:resultDic];
                    }];
                } else {
                    [self showToastWithMsg:[NSString stringWithFormat:@"code:%@\ndesc:%@",  [resultDic objectForKey:@"resultCode"], [resultDic objectForKey:@"desc"]]];
                }
            });
        }];
    }
}


#pragma mark - 关闭按钮事件
- (void)backButtonAction:(UIButton *)sender{
    __weak typeof(self) weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        [weakSelf sendNextHander:DGGMobileLoginStatusCancel token:nil errorInfo:nil];
    }];
}

#pragma mark - 切换登录事件
- (void)otherLoginButtonAction:(UIButton *)sender{
    __weak typeof(self) weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        [weakSelf sendNextHander:(DGGMobileLoginStatusChange) token:nil errorInfo:nil];
    }];
}

#pragma mark - 操作统一处理
- (void)sendNextHander:(DGGMobileLoginStatus)type token:(NSString *)token errorInfo:(NSDictionary *)errorInfo{
    if(self.loginAuthResultBlock){
        self.loginAuthResultBlock(type, token, errorInfo);
    }
    if(type == DGGMobileLoginStatusSuccess){
        if([self.delegate respondsToSelector:@selector(dgg_telecomLoginSuccess:loginStatus:accessToken:)]){
            [self.delegate dgg_telecomLoginSuccess:self loginStatus:type accessToken:token];
        }
    }else if(type == DGGMobileLoginStatusFailure || type == DGGMobileLoginStatusPreGetPhoneFailure){
        if([self.delegate respondsToSelector:@selector(dgg_telecomLoginFailure:loginStatus:errorInfo:)]){
            [self.delegate dgg_telecomLoginFailure:self loginStatus:type errorInfo:errorInfo];
        }
    }else if(type == DGGMobileLoginStatusChange){
        if([self.delegate respondsToSelector:@selector(dgg_telecomLoginChangeType:loginStatus:)]){
            [self.delegate dgg_telecomLoginChangeType:self loginStatus:type];
        }
    }else if(type == DGGMobileLoginStatusCancel){
        if([self.delegate respondsToSelector:@selector(dgg_telecomLoginCancelType:loginStatus:)]){
            [self.delegate dgg_telecomLoginCancelType:self loginStatus:type];
        }
    }
}

#pragma mark - 协议勾选事件
- (void)checkAgreeButtonAction:(UIButton *)sender{
    self.isAgree = !self.isAgree;
    if(self.isAgree){
        [self.checkAgreeButton setImage:[UIImage imageNamed:kMobileLoginSource(@"mobileLogin_checked.png")] forState:UIControlStateNormal];
        self.loginButton.backgroundColor = self.loginButtonBgColor;
    }else{
        [self.checkAgreeButton setImage:[UIImage imageNamed:kMobileLoginSource(@"mobileLogin_unchecked.png")] forState:UIControlStateNormal];
        self.loginButton.backgroundColor = [self.loginButtonBgColor colorWithAlphaComponent:.5];
    }
}

- (void)bindData{
    UIImage *logoImage = [DGGMobileLoginConfig sharedInstance].appLogoImage;
    if(!logoImage){
        logoImage = [UIImage imageNamed:kMobileLoginSource(@"ctc.png")];
    }
    self.logoImageView.image = logoImage;
    NSString *prefix = [DGGMobileLoginConfig sharedInstance].appPrivacyPrefix;
    NSMutableString *appPrivacyStr = [NSMutableString stringWithFormat:@"%@%@",prefix,dianxinServiceName];
    NSArray *apprivacyArray = self.appPrivacyArray;
    NSInteger agreeMentCount = apprivacyArray.count;
    for (int i = 0; i < agreeMentCount; i++) {
        DGGAgreementListModel *model = apprivacyArray[i];
        if(i == (agreeMentCount - 1)){
            [appPrivacyStr appendFormat:@"和%@", model.title];
        }else{
            [appPrivacyStr appendFormat:@"、%@", model.title];
        }
    }
    NSString *suffix = [DGGMobileLoginConfig sharedInstance].appPrivacySuffix;
    [appPrivacyStr appendString:suffix];
    NSMutableArray *handleArray = @[].mutableCopy;
    [handleArray addObjectsFromArray:apprivacyArray];
    DGGAgreementListModel *firstModel = [[DGGAgreementListModel alloc] init];
    firstModel.title = dianxinServiceName;
    firstModel.urlString = dianxinServiceURL;
    [handleArray insertObject:firstModel atIndex:0];
    NSInteger handleArrayCount = handleArray.count;
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:appPrivacyStr];
    for (int i = 0; i < handleArrayCount; i++) {
        DGGAgreementListModel *tempModel = handleArray[i];
        if(tempModel.title && tempModel.urlString){
            NSString *valueString1 = tempModel.urlString;
            [attrStr addAttribute:NSLinkAttributeName value:valueString1 range:[attrStr.string rangeOfString:tempModel.title]];
        }
    }
    [attrStr addAttributes:@{NSForegroundColorAttributeName:self.appPrivacyContentColor} range:NSMakeRange(0, attrStr.length)];
    self.agreeLabel.delegate = self;
    self.agreeLabel.attributedText = attrStr;
    self.agreeLabel.linkTextAttributes = @{NSForegroundColorAttributeName:self.appPrivacyColor};
}

#pragma mark - 处理点击协议方法
- (void)handleAgreementWithURL:(NSURL *)URL{
    BOOL isFind = NO;
    NSArray *apprivacyArray = self.appPrivacyArray;
    DGGAgreementListModel *targetModel = nil;
    for (DGGAgreementListModel *model in apprivacyArray) {
        if(model.urlString && [URL.absoluteString isEqualToString:model.urlString]){
            isFind = YES;
            targetModel = model;
            break;
        }
    }
    if([URL.absoluteString isEqualToString:dianxinServiceURL]){
        DGGMobileLoginServiceViewController *serviceVC = [[DGGMobileLoginServiceViewController alloc] init];
        serviceVC.serviceHTML = URL.absoluteString;
        serviceVC.navTitle = dianxinServiceName;
        [self.navigationController pushViewController:serviceVC animated:YES];
    }else if (isFind){
        DGGMobileLoginServiceViewController *serviceVC = [[DGGMobileLoginServiceViewController alloc] init];
        serviceVC.serviceHTML = targetModel.urlString;
        if(targetModel.webTitle && ![targetModel.webTitle isEqualToString:@""]){
            serviceVC.navTitle = targetModel.webTitle;
        }else{
            serviceVC.navTitle = targetModel.title;
        }
        [self.navigationController pushViewController:serviceVC animated:YES];
    }
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction API_AVAILABLE(ios(10.0)){
    [self handleAgreementWithURL:URL];
    return NO;
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    [self handleAgreementWithURL:URL];
    return NO;
}

- (UIActivityIndicatorView *)activityIndicator{
    if(!_activityIndicator){
        _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        UIColor *pageThemeColor = self.pageThemeColor;
        [_activityIndicator setColor:pageThemeColor];
        [self.view addSubview:_activityIndicator];
    }
    return _activityIndicator;
}

#pragma mark - AlertView辅助工具
- (void)showToastWithMsg:(NSString *)msg{
    if (@available(iOS 8.0, *)) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:msg
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:NO completion:nil];
    } else {
        // Fallback on earlier versions
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

- (void)dealloc{
    NSLog(@"%@ %@",NSStringFromClass(self.class),NSStringFromSelector(_cmd));
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
